<?php
/**
 * wap2.0 购物流程 - 订单提交
 */

$address_id 	= empty($_POST['address_id']) ? 0 : trim($_POST['address_id']);
$area_id 		= empty($_POST['area_id']) ? 0 : $_POST['area_id'];
$area_name 		= empty($_POST['area_name']) ? '' : trim($_POST['area_name']);
$transport_day 	= empty($_POST['transport_day']) ? 0 : intval($_POST['transport_day']);
$pay_type 		= empty($_POST['pay_type']) ? 0 : intval($_POST['pay_type']);
$favourable_id 	= empty($_POST['favourable_id']) ? 0 : trim($_POST['favourable_id']);
$invoice 		= empty($_POST['invoice']) ? '' : trim($_POST['invoice']);
$remark 		= empty($_POST['remark']) ? '' : trim($_POST['remark']);

$wallet			= empty($_POST['wallet']) ? 0 : intval($_POST['wallet']);
$pay_password	= empty($_POST['wallet_password']) ? '' : trim($_POST['wallet_password']);

$favourable_id && $favourable_id = base64_decode($favourable_id);

$now = local_time();

// 如果无收货地址ID
if (!$address_id)
{
	wap_header("Location: index.php?m=user&act=address&step=edit&filter=add");
}

/* 获取 购物车 */
//$cart_info = $mInterface->getShopCart($user_token);
$cart_info = $mInterface->getShopCartNew($user_token);

if (empty($cart_info) || !is_array($cart_info))
{
	show_message('购物袋为空', '返回购物', 'index.html', 'warning');
}

// 获取美妆品牌ID
$beauty = get_beauty_brand_products($cat_id,$sort,$filter_stock);
$beauty_brands = $beauty['brand_ids'];
$in_beauty = false;

$total = array('amount'=>0, 'count'=>0,'favourable_money'=>0,'cod_total'=>0);

/*foreach ($cart_info AS $val)
 {
 $total['amount'] += $val['num'] * $val['sexmall_price'];
 $total['count'] += $val['num'];

 $pl[] = ';'.$val['product_id'].';'.$val['num'].';'.($val['sexmall_price']*$val['num']);

 if (!$in_beauty && in_array($val['brand_id'], $beauty_brands)){
 $in_beauty = true;
 }
 }*/

#############################
$cart_id = $pms_hash = array();
$orders_num = count($cart_info['orders_detail']);
foreach ($cart_info['orders_detail'] AS $key => $val){
	foreach ($val['order_goods'] AS $k => $v){
		// 过滤异常数据
		if (!is_array($v)){
			unset($cart_info['orders_detail'][$key]['order_goods'][$k]);
			continue;
		}

		if (!$in_beauty && in_array($v['brand_id'], $beauty_brands)){
			$in_beauty = true;
		}

		// OMNITURE 统计
		$pl[] = ';'.$v['product_id'].';'.$v['num'].';'.$v['sum_price'];
	}

	if ($val['order_info']['brand_id'] == 0){
		$total['cod_total'] += $val['order_info']['total'];
	}

	if ($pay_type == 8 && $val['order_info']['brand_id']){
		continue;
	}

	$cart_id[] = $val['order_info']['brand_id'];
	$pms_hash[] = $val['active_data']['hash'];

	$total['ex_fav_money'] = $val['active_data']['ex_fav_money'];
}

$total['count'] = isset($cart_info['goods_count']) ? $cart_info['goods_count'] : 0;
$total['amount'] = isset($cart_info['orders_total']) ? $cart_info['orders_total'] : 0;
############################


/* 检查 货到付款 金额、地域限制
 * 商品总额小于11元或大于3000元暂不支持货到付款
 * 部分地区不支持货到付款
 */
if ($pay_type == 8)
{
	if ($total['cod_total'] < COD_MONEY_MIN || $total['cod_total'] > COD_MONEY_MAX){
		show_message('订单提交失败：商品总额小于'.COD_MONEY_MIN.'元或大于'.COD_MONEY_MAX.'元暂不支持货到付款', '返回', 'flow-checkout.html', 'warning');
	}

	$isCod = $mInterface->getShopAreaDelivery($area_id);
	if ( empty($isCod['return']) || !$isCod['return'] ){
		show_message('订单提交失败：'.$area_name.'暂不支持货到付款', '返回', 'flow-checkout.html', 'warning');
	}
}

/**
 * 订单渠道统计
 * 1.优先使用cps cookie (注：cps cookie WAP端 只读不写)
 * 2.没有cps cookie时，则使用from参数
 */
$standby_id = '';
$standby_id = $cps = wap_getcookie('cps',false);
$from = wap_getcookie("WAP[from]");
$from = preg_replace(array('/[\W]/'), '', $from);

if(!empty($from) && empty($standby_id))
{
	//如果存在u参数就替换STANDBY
	$cps_u = wap_getcookie('cps_u');
	$standby_id = ($cps_u ? $cps_u : STANDBY) . $from;
}


/* 提交订单 */
$cart_id = implode(',', $cart_id);
$pms_hash = implode(',', $pms_hash);
$orders = $mInterface->submitShopOrderNew($user_token,$address_id,$transport_day,$pay_type,$cart_id,$pms_hash,$favourable_id,$invoice,$remark,$standby_id);
//var_dump($orders);exit;

// 判断是否全部订单都已提交
$orders_all_commit = 1;
if (count($orders) < $orders_num){
	$orders_all_commit = 0;
}

/* 订单提交成功 */
if (is_array($orders) && !empty($orders))
{
	/* 付款方式 */
	//$payment_list = get_payment_list();

	$total = array('money'=>0, 'favourable_money'=>0);
	$order_sn = array();
	foreach ($orders AS $key => $val)
	{
		$order_sn[] = $val['order_sn'];

		$total['money'] += $val['money'];
		$total['favourable_money'] += $val['favourable_money'];

		$pay_type = $val['pay_type'];

		// 唯品钱包支付
		if ($pay_type == 10){
			$orders[$key]['pay_type_name'] .= '钱包支付';
		}
		else
		{
			/*foreach ((array)$payment_list AS $v)
			 {
				if ($v['paytype_id'] == $val['pay_type']){
				$orders[$key]['pay_type_name'] = $v['paytype_name'];
				break;
				}
				}*/

			// 货到付款
			if ($pay_type == 8){
				$orders[$key]['pay_type_name'] = '货到付款';
			}else{
				$orders[$key]['pay_type_name'] = '在线支付';
			}

			//$orders[$key]['pay_type_name'] = $orders[$key]['pay_type_name'] ? $orders[$key]['pay_type_name'] : '在线支付';
			if ($wallet){
				$orders[$key]['pay_type_name'] .= ' + 钱包支付';
			}
		}

		// 获取商品分类
		$goods_category = $mInterface->order_goods_category($val['order_sn']);
		$goods_category = $goods_category['data'][0];
		$goods_category['order_sn'] = $val['order_sn'];
		$goods_category['money'] = $val['money'];
		$goods_category['pay_type_name'] = $orders[$key]['pay_type_name'];
		$goods_category['carriage'] = $orders[$key]['carriage'];
		$goods_category['favourable_money'] = $orders[$key]['favourable_money'];

		$order_data[] = $goods_category;
	}

	$total['use_wallet'] = $wallet;


	/* 删除COOKIE */
	wap_setcookie("WAP[clear_time]");
	wap_setcookie("WAP[favourable_id]");
	wap_setcookie("WAP[address_id]");

	// 删除memcache
	$mem->del('cart_info');


	/**
	 * omniture订单统计
	 */
	include 'omniture/flow_done.php';


	/* 渠道统计订单 */
	if($from)
	{
		foreach ($order_data AS $val){
			$canal_data = array(
				'canal_id'	=> $from,
				'order_sn'	=> $val['order_sn'],
				'money'		=> $val['money'],
				'new_customer'	=> $val['data4'],
				'date_time'	=> date('Y-m-d', $now),
				'addtime'	=> $now
			);
			$csm=canalStatisticsManage::singleton($db);
			$csm->AddCanalOrderArr($canal_data);
		}
	}

	/* 亿起发cps订单统计 */
	include ROOT_PATH . 'includes/modules/cps/yima.php';

	/* 渠道订单统计 */
	include ROOT_PATH . 'includes/modules/cps/canal.php';


	/* 在线支付(移动支付、wap支付宝) */
	if ((!$wallet || $total['money']) && ((defined('OPEN_MOBILE_PAY') && OPEN_MOBILE_PAY != 'off' && $pay_type == 49)
	|| (defined('OPEN_ALIPAY_PAY') && OPEN_ALIPAY_PAY != 'off' && $pay_type == 50)) )
	{
		/* 跳转到支付页面 */
		if ($pay_type == 49)
		{
			$url = MOBILE_PAY_URL;
			$verify_key = MOBILE_PAY_VERIFY_KEY;
		}
		else if ($pay_type == 50)
		{
			//$url = ALIPAY_PAY_URL;
			$url = 'http://pay.sexmall.com/public/operate.php';
			$verify_key = ALIPAY_PAY_VERIFY_KEY;
		}

		$data = array(
			'orders'	=> implode(',', $order_sn),
			'pay_type'	=> $pay_type,
			'pay_id'	=> 1,
			'bank_id'	=> ''
			);

			$url = $url . '?' . http_build_query($data);

			$smarty->assign('pay_url', $url);

			wap_header("Refresh: 1; url=" . $url);
	}

}
else if ($orders == 'BLACK_LIST_NOT_ALLOW_COD'){
	show_message('您的账号不允许货到付款，请改用在线支付', '重新提交', 'flow-checkout.html', 'warning');
}
else if ($orders == 'PAY_PASSWORD_ERROR'){
	show_message('钱包支付密码错误', '重新提交', 'flow-checkout.html', 'warning');
}
else if ($orders == 'PAY_PASSWORD_EMPTY'){
	show_message('请输入钱包支付密码', '重新提交', 'flow-checkout.html', 'warning');
}
else
{
	show_message('订单提交失败', '重新提交', 'flow-checkout.html', 'warning');
}


// 返回最后购物的品牌
$last_addtocart_brand = wap_getcookie("WAP[brd_lst_addtocart]");
if (in_array($last_addtocart_brand, $beauty_brands)){
	$smarty->assign('in_beauty', 1);
}

$smarty->assign('orders', 			$orders);
$smarty->assign('total', 			$total);
$smarty->assign('pay_type', 		$pay_type);
$smarty->assign('is_supplier', 		$cart_info['is_supplier']);

$smarty->assign('orders_all_commit', $orders_all_commit);


$smarty->assign('last_addtocart_brand', $last_addtocart_brand);

$show = wap_getcookie("WAP[show]") ? wap_getcookie("WAP[show]") : 2;
$smarty->assign('show', $show);

$smarty->assign('title', '提交订单');

$smarty->display('flow_done.dwt');
